package com.markerhub.handler;

import com.markerhub.common.lang.Result;
import com.markerhub.exception.ApiException;
import com.markerhub.exception.RuntimeApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;


/**
 * @Author by MaXiaofeng
 * @Description 异常报错消息处理类
 * @Date 2022/2/20 10:45
 * @Version 1.0.0
 */
@ControllerAdvice
public class GlobalExceptionAdvice {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionAdvice.class);

    /**
     * 处理自定义的业务异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = RuntimeApiException.class)
    @ResponseBody
    @ResponseStatus
    public Result ApiExceptionHandler(HttpServletRequest req, RuntimeApiException e) {
        logger.error("发生业务异常！原因是：{}", e.getErrorMsg());
        return Result.fail(e.getErrorCode(), e.getErrorMsg());
    }

    /**
     * 处理自定义的业务异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = ApiException.class)
    @ResponseBody
    @ResponseStatus
    public Result RunTimeExceptionHandler(HttpServletRequest req, ApiException e) {
        logger.error("发生业务异常！原因是：{}", e.getErrorMsg());
        return Result.fail(e.getErrorCode(), e.getErrorMsg());
    }

    /**
     * 当发生java.lang.NumberFormatException: null报错时，大概率是因为参数上传为空
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = NumberFormatException.class)
    @ResponseBody
    @ResponseStatus
    public Result NullParameterExceptionHandler(HttpServletRequest req, NumberFormatException e) {
        logger.error("发生业务异常！原因是：{}", "上传参数异常");
        return Result.fail(809, "出错:上传的参数异常");
    }

//    /**
//     * 处理空指针的异常
//     *
//     * @param req
//     * @param e
//     * @return
//     */
//    @ExceptionHandler(value = NullPointerException.class)
//    @ResponseBody
//    public Result exceptionHandler(HttpServletRequest req, NullPointerException e) {
//        logger.error("发生空指针异常！原因是:", e);
//        return Result.fail(ApiExceptionCodes.BODY_NOT_MATCH.getValue(), "空指针异常");
//    }
//
//    /**
//     * 处理其他异常
//     *
//     * @param req
//     * @param e
//     * @return
//     */
//    @ExceptionHandler(value = Exception.class)
//    @ResponseBody
//    public Result exceptionHandler(HttpServletRequest req, Exception e) {
//        logger.error("未知异常！原因是:", e);
//        return Result.fail(ApiExceptionCodes.INTERNAL_SERVER_ERROR.getDesc(), ApiExceptionCodes.INTERNAL_SERVER_ERROR.getDesc());
//    }
}
